package com.lovegu.netty.coder;

import com.lovegu.netty.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;

/**
 * @author 老顾 1437594522@qq.com
 * @description Kryo序列化-自定义编码器
 * @date 2022/11/22 21:59
 */
@AllArgsConstructor
public class NettyKryoEncoder extends MessageToByteEncoder<Object> {

    private final Serializer serializer;
    private final Class<?> genericClass;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (genericClass.isInstance(o)){
            //1、将对象转换为byte
            byte[] body = serializer.serialize(o);
            //2、读取消息的长度
            int dataLength = body.length;
            //3、写入消息对应的字节数组长度，writerIndex 加4
            byteBuf.writeInt(dataLength);
            //4、将字节数组写入ByteBuf对象中
            byteBuf.writeBytes(body);
        }
    }
}
